import { _decorator, Component, instantiate, Node, Vec3 } from 'cc';
import { GAME_PREFAB, GlobalData } from '../../../Data/GlobalData';
import { SingleButtle } from './SingleButtle';
import { EffectLoad } from '../EffectLoad/EffectLoad';
const { ccclass, property } = _decorator;

@ccclass('ButtleLoad')
/**
 * 子弹层
 */
export class ButtleLoad extends Component {


    //子弹数组
    private ButtleArr: Node[] = [];

    private Nouse: Node[] = [];

    //效果层
    @property(EffectLoad)
    private EffectLoad: EffectLoad = null;

    /**
     * 初始化
     */
    public Init() {
        for (let sb of this.ButtleArr) {
            sb.setParent(null);
            this.Nouse.push(sb);
        }
        this.ButtleArr = [];
    }

    /**
     * 创建子弹
     */
    public CreateButtle(_pos: Vec3, _angle: number, _gunindex: number, _fllownode: Node) {

        if (this.Nouse.length > 0) {
            let sb: Node = this.Nouse.pop();
            this.node.addChild(sb);
            sb.setWorldPosition(_pos);
            sb.angle = _angle;
            sb.getComponent(SingleButtle).UpdateButtle(_gunindex, _fllownode);
            this.ButtleArr.push(sb);
            return;
        }

        let sb: Node = instantiate(app.resManager.Prefabs[GAME_PREFAB.SingleButtle]);
        this.node.addChild(sb);
        sb.setWorldPosition(_pos);
        sb.angle = _angle;
        sb.getComponent(SingleButtle).UpdateButtle(_gunindex, _fllownode);
        this.ButtleArr.push(sb);
    }

    protected update(dt: number): void {
        if (GlobalData.GameOver) return;

        for (let i = 0; i < this.ButtleArr.length; i++) {
            this.ButtleArr[i].getComponent(SingleButtle).UpdatePosition();

            if (this.ButtleArr[i].getComponent(SingleButtle).ReturnIsHit()) {
                this.EffectLoad.CreateEffect(this.ButtleArr[i].getWorldPosition());
                this.ButtleArr[i].setParent(null);
                this.Nouse.push(this.ButtleArr[i]);
                this.ButtleArr.splice(i, 1);
                i--;
            }
        }

    }

}


